package com.yiguantong.police.qrCode.ui;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiguantong.police.R;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.yiguantong.police.BaseActivity;
import com.yiguantong.police.qrCode.utils.camera.CameraManager;
import com.yiguantong.police.qrCode.utils.decoding.CaptureActivityHandler;
import com.yiguantong.police.qrCode.utils.view.ViewfinderView;

import java.io.IOException;
import java.util.Vector;

public class CaptureActivity extends BaseActivity implements Callback, OnClickListener {
    private CaptureActivityHandler handler;

    private ViewfinderView viewfinderView;

    private boolean hasSurface;

    private Vector<BarcodeFormat> decodeFormats;

    private String characterSet;

    private MediaPlayer mediaPlayer;

    private boolean playBeep;

    private static final float BEEP_VOLUME = 0.10f;

    private boolean vibrate;

    /**
     * 闪光灯的布局
     */
    private LinearLayout flashlightBtn;

    /**
     * 闪光灯ImageView
     */
    private ImageView flashIv;

    /**
     * 闪光灯TextView
     */
    private TextView flashTextView;

    /**
     * 是否打开闪光灯
     */
    private boolean isOpenFlashLight;

    private SurfaceHolder surfaceHolder;
    private boolean fromWebView;
    //H5扫描结果直接返回
    private boolean simpleScanner;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture);
//        initToolbar(getResources().getString(R.string.qrcode_title), ToolbarMenuEnum.PopupIcon);
        // 初始化 CameraManager
        CameraManager.init(getApplication());
        viewfinderView = findViewById(R.id.viewfinder_view);
        hasSurface = false;
        flashlightBtn = findViewById(R.id.bottom_layout);
        flashIv = this.findViewById(R.id.flash_iv);
        flashTextView = this.findViewById(R.id.flash_tv);
        flashlightBtn.setOnClickListener(this);
        fromWebView = getIntent().getBooleanExtra("fromWebView", false);
        simpleScanner = getIntent().getBooleanExtra("simpleScanner", false);
//        twoDimensionPostRequest("http://192.168.31.84:8080/test1/test/erweima?param1=23423423");
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onResume() {
        super.onResume();
        // 这里就是一系列初始化相机view的过程
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        // 这里就是看看是否是正常声音播放模式，如果是就播放声音，如果不是，则不播放
        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        // 初始化声音
        initBeepSound();
        // 是否震动
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 关掉相机，关掉解码线程，清空looper队列中message
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        CameraManager.get().closeDriver();// 关掉相机
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 初始化相机
     */
    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            // 新建解码结果handler
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // 初始化相机
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    /**
     * 返回显示的view
     */
    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    /**
     * 返回处理解码结果的handler
     */
    public Handler getHandler() {
        return handler;
    }

    /**
     * 清空view中先前扫描成功的图片
     */
    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    public void handleDecode(Result obj, Bitmap barcode) {

        /**
         * 播放jeep声音
         */
        playBeepSoundAndVibrate();

        /**
         * 显示解码字符串
         */
        String content = obj.getText();
        if (TextUtils.isEmpty(content)) {
            closeFlashLigth();
            CaptureActivity.this.finish();
            return;
        }
        //H5页面扫描结果，将扫描结果直接返回H5页面
        if (fromWebView && simpleScanner) {
            Intent intent = new Intent();
            intent.putExtra("sResult", content);
            setResult(RESULT_OK, intent);
            CaptureActivity.this.finish();
            closeFlashLigth();
        } else {
            // 其他情况不做处理
            closeFlashLigth();
            CaptureActivity.this.finish();
        }
    }


    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
                        file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    /**
     * 震动时间
     */
    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        /**
         * 播放声音
         */
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        /**
         * 震动
         */
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }

    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bottom_layout:
                if (!isOpenFlashLight) {
                    openFlashLight();
                } else {
                    closeFlashLigth();
                }
                break;

            default:
                break;
        }
    }

    private void closeFlashLigth() {
        isOpenFlashLight = false;
        flashTextView.setText("开灯");
        flashTextView.setSelected(false);
        flashlightBtn.setSelected(false);
        flashIv.setSelected(false);
        CameraManager.get().offLight();
    }

    private void openFlashLight() {
        isOpenFlashLight = true;
        flashTextView.setText("关灯");
        flashTextView.setSelected(true);
        flashlightBtn.setSelected(true);
        flashIv.setSelected(true);
        CameraManager.get().openLight();
    }

}